import axios from "axios";
import qs from "qs";
import { notification, Icon } from "antd";
import router from "umi/router";
import CryptoJS from "crypto-js";
import UserSession from "@/UserSession";

const baseSuffix = "/cloud";

// function checkStatus(status, msg) {
//   notification.error({
//     message: msg,
//   });
// }
const key = "notificationKey"; // 设置消息通知框唯一的key

//  是的需要加上headquarters的url
const needAddHeadquartersUrls = [
	"/qa/list",
	"/qa/disabled",
	"/base/model/list",
	"/base/model/word/list",
	"/base/slot/list/model",
	// "/base/slot/list",
	"/dialog/slot/list",
	"/qa/list/slot",
	"/base/slot/info",
	"/qa/keyword/list",
	// "/base/api/list",
	"/base/api/info",
	"/graph/list",
	"/dialog/getDialogs",
	"/base/wordsyn/list",
	"/base/dict/list",
	"/qa/id",
	"/base/api/info",
	// "/qa/keyword/info",
	// "/base/slot/list/ids",
	// "/qa/relqa/list",
	// "/qa/category/tree",
	"/graph/category/info",
	"/rootCategory/list",
	"/rootCategory/add",
	"/rootCategory/delete",
	"/rootCategory/disabled",
	"/dialog/category/info",
	"/rootCategory/listShare",
	"/graph/info",
	"/dialog/getStatusById",
	"/dialog/getDialogTemplate",
	"/dialog/getDialogTemplate",
	"/dialog/getDialogSlots",
	"/dialog/stage",
	"/graph/node/info",
	"/dialog/flowAction/stage",
	"/api/actionApi/loadActionApis",
	"/dialog/setting",
	"/robot/categoryConfig/qa/info",
	"/robot/categoryConfig/atlas/info",
	"/robot/categoryConfig/dialog/info",
	"/robot/categoryConfig/keyword/info",
];
const needAddAdminUrls = [
	"/llm/use/list",
	"/questionTemplateCategory/list",
	"/embeddingModel/list",
];

function checkStatus(status, msg) {
	if (status === 401) {
		notification.open({
			key,
			message: msg,
			icon: <Icon type='close-circle' style={{ color: "red" }} />,
		});
		window.g_app._store.dispatch({
			type: "login/logout",
		});
		localStorage.clear();
		return;
	}
	// environment should not be used
	if (status === 403) {
		router.push("/exception/403");
		return;
	}
	if (status <= 504 && status >= 500) {
		router.push("/exception/500");
		return;
	}
	if (status >= 404 && status < 422) {
		router.push("/exception/404");
	}
	if (status === 402) {
		return notification.open({
			key,
			message: msg,
			icon: <Icon type='close-circle' style={{ color: "red" }} />,
		});
	}

	return notification.open({
		key,
		message: msg,
		icon: <Icon type='close-circle' style={{ color: "red" }} />,
	});
}

const Req = axios.create({
	// baseURL: '',
	// withCredentials: true,
});

function apiRobotFormData(method, baseURL, url, params, response) {
	console.log(`apiRobotFormData【${baseURL}${url}】`);
	const currentTime = new Date().getTime();
	const currentLocation = UserSession.getCurrentLocation();

	// 是不是系统知识库，如果是系统知识库，url需要加上headquarters
	const isSystem = currentLocation.indexOf("systemKnowledge") > -1;
	const isNeedAddHeadquarters = needAddHeadquartersUrls.indexOf(url) > -1;
	const isNeedAddAdmin = needAddAdminUrls.indexOf(url) > -1;
	return new Promise((resolve) => {
		Req({
			method,
			url: (isSystem || (params && params.urlPrefix)) && isNeedAddHeadquarters ? `${url}/headquarters` : (params && params.urlPrefix) && isNeedAddAdmin ? `${url}/admin` : `${url}`,
			data: method === "POST" || method === "PUT" ? params : null,
			params: method === "GET" || method === "DELETE" ? params : null,
			baseURL,
			headers: {
				"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
				Authorization: url === "/login" ? "" : `Bearer ${UserSession.getToken()}`,
				lid: currentTime,
				sign: encrypt(JSON.stringify(currentTime)),
			},
			transformRequest: [
				function(data) {
					let ret = "";
					for (const it in data) {
						ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&`;
					};
					ret = ret.substring(0, ret.lastIndexOf("&"));
					return ret;
				},
			],
		}).then(function(res) {
			if (res.data.code === 0) {
				if (res.data.data && typeof res.data.data === "object") {
					resolve(res.data.data);
				} else {
					resolve({
						status: res.data.status ? res.data.status : false,
						msg: res.data.msg ? res.data.message ? res.data.message : res.data.msg : "操作成功",
						data: res.data.data,
						message: res.data.message ? res.data.message : "操作成功",
					});
				}
			} else if (url === "/login" || url === "/robot/add") {
				checkStatus(res.data.code, res.data.message);
				resolve(res.data);
			} else {
				checkStatus(res.data.code, res.data.message);
				resolve(res.data);
			}
		}).catch((err) => {
			// console.log(err.response.status);
			// checkStatus(err.response.status);
		});
	});
}

function apiRobot(method, baseURL, url, params, response) {
	console.log(`apiRobot【${baseURL}${url}】`, params);
	const currentTime = new Date().getTime();
	const isNeedAddHeadquarters = needAddHeadquartersUrls.indexOf(url) > -1;
	const currentLocation = UserSession.getCurrentLocation();
	// 是不是系统知识库，如果是系统知识库，url需要加上headquarters
	const isSystem = currentLocation.indexOf("systemKnowledge") > -1;
	const isNeedAddAdmin = needAddAdminUrls.indexOf(url) > -1;
	return new Promise((resolve) => {
		Req({
			method,
			url: (isSystem || (params && params.urlPrefix)) && isNeedAddHeadquarters ? `${url}/headquarters` : (params && params.urlPrefix) && isNeedAddAdmin ? `${url}/admin` : `${url}`,
			data: method === "POST" || method === "PUT" ? params : null,
			params: method === "GET" || method === "DELETE" ? params : null,
			baseURL,
			headers: {
				"Content-Type": "application/json;charset=UTF-8",
				Authorization: url === "/login" || url === '/auth' || url === "/getSystemPlatformInfo" || url === "/doc/milvusSearchDoc" ? "" : `Bearer ${UserSession.getToken()}`,
				lid: currentTime,
				sign: encrypt(JSON.stringify(currentTime)),
			},
			transformRequest: [
				function(data) {
					return JSON.stringify(data);
				},
			],
		}).then(function(res) {
			console.log(res, url);
			if (res.data.code === 0) {
				if (res.data.data && typeof res.data.data === "object") {
					if (
						url === "/channel/getChannelInfoByApplicationId" ||
						url === '/qa/getQaRootCategoryAllQaSync' ||
						url === '/knowledgeCollect/generateAnswersRadio' ||
						url === '/doc/getDocById'
					) {
						resolve(res.data);
					} else {
						resolve(res.data.data);
					}
				} else {
					resolve({
						code: res.data.code,
						status: res.data.status ? res.data.status : false,
						msg: res.data.msg ? res.data.message ? res.data.message : res.data.msg : "操作成功",
						data: res.data.data,
						message: res.data.message ? res.data.message : "操作成功",
					});
				}
			} else if (
				url === "/login" ||
				url === "/qa/edit" ||
				url === "/dialog/getProgress" ||
				url === "/qa/add" ||
				url === "/base/api/test" ||
				url === "/dialog/template" ||
				url === "/robot/categoryConfig/qa/edit" ||
				url === "/robot/categoryConfig/atlas/edit" ||
				url === "/robot/categoryConfig/dialog/edit" ||
				url === "/robot/categoryConfig/keyword/edit" ||
				url === "/qa/move" ||
				url === "/qa/disabled" ||
				url === "/userTag/add" ||
				url === "/userTag/update" ||
        		url === "/baseContact/fullSync"
			) {
				checkStatus(res.data.code, res.data.message);
				resolve(res.data);
			} else if (url === '/qa/getQaRootCategoryAllQaSync') {
				resolve(res.data);
			} else {
				if (url === "/stat/chatRecord/relate") {
					resolve(res.data);
				} else if (url === "/doc/previewDoc") {
					resolve(res);
				};;
				checkStatus(res.data.code, res.data.message);
				resolve(res.data);
			}
		}).catch((err) => {
			// console.log(err.response.status);
			// checkStatus(err.response.status);
		});
	});
}

function download(method, baseURL, url, params, response) {
	console.log(`download【${baseURL}${url}】`);
	// if(hasSign){
	//   let enParams = params ? params : {}
	//   const encryptParam = encrypt(JSON.stringify(enParams))
	//   enParams.sign = encryptParam
	//   params = enParams
	// };
	const currentTime = new Date().getTime();
	return new Promise((resolve) => {
		const headData = {
			"Content-Type": "application/x-www-form-urlencoded",
			Authorization: url === "/login" ? "" : `Bearer ${UserSession.getToken()}`,
			lid: currentTime,
			sign: encrypt(JSON.stringify(currentTime)),
		};
		const data = qs.stringify(params);
		const newUrl = `${url}?${data}`;
		axios.get(baseURL + newUrl, { headers: headData, responseType: "blob" }).then((res) => {
			const blob = new Blob([res.data]);
			const fileName = decodeURIComponent(
				res.headers["content-disposition"].split("=")[1]
			);
			if (window.navigator.msSaveOrOpenBlob) {
				navigator.msSaveBlob(blob, fileName);
			} else {
				const link = document.createElement("a");
				const evt = document.createEvent("HTMLEvents");
				evt.initEvent("click", false, false);
				link.href = URL.createObjectURL(blob);
				link.download = fileName;
				link.style.display = "none";
				document.body.appendChild(link);
				link.click();
				window.URL.revokeObjectURL(link.href);
			}
		});
	});
}

function downloadForPost(method, baseURL, url, params, response) {
	// if(hasSign){
	//   let enParams = params ? params : {}
	//   const encryptParam = encrypt(JSON.stringify(enParams))
	//   enParams.sign = encryptParam
	//   params = enParams
	// };
	const currentTime = new Date().getTime();
	console.log(`download【${baseURL}${url}】`);
	return new Promise((resolve) => {
		const headData = {
			"Content-Type": "application/json;charset=UTF-8",
			Authorization: url === "/login" ? "" : `Bearer ${UserSession.getToken()}`,
			lid: currentTime,
			sign: encrypt(JSON.stringify(currentTime)),
		};
		// axios.post(baseURL + url, params, { headers: headData, responseType: 'blob' }).then(res => {
		//   if (res.data && res.data.code == -1) {
		//     resolve(res.data);
		//     return;
		//   } else {
		//     resolve({ code: 0, msg: '导出成功', data: null });
		//   }
		//   const blob = new Blob([res.data]);
		//   const fileName = decodeURIComponent(res.headers['content-disposition'].split('=')[1]);
		//   if (window.navigator.msSaveOrOpenBlob) {
		//     navigator.msSaveBlob(blob, fileName);
		//   } else {
		//     const link = document.createElement('a');
		//     const evt = document.createEvent('HTMLEvents');
		//     evt.initEvent('click', false, false);
		//     link.href = URL.createObjectURL(blob);
		//     link.download = fileName;
		//     link.style.display = 'none';
		//     document.body.appendChild(link);
		//     link.click();
		//     window.URL.revokeObjectURL(link.href);
		//   }
		// });
		fetch(baseURL + url, {
			method: "POST",
			body: JSON.stringify(params),
			headers: headData,
		}).then(async (res) => {
			if (res.headers.get("content-type").indexOf("application/json") !== -1) {
				const data = await res.json();
				if (data && data.code == -1) {
					resolve(data);
					return;
				}
			}
			res.blob().then((blob) => {
				const fileName = decodeURIComponent(
					res.headers.get("content-disposition").split("=")[1]
				);
				resolve({ code: 0, status: true, msg: "下载成功", data: true });
				if (window.navigator.msSaveOrOpenBlob) {
					navigator.msSaveBlob(blob, fileName);
				} else {
					const link = document.createElement("a");
					const evt = document.createEvent("HTMLEvents");
					evt.initEvent("click", false, false);
					link.href = URL.createObjectURL(blob);
					link.download = fileName;
					link.style.display = "none";
					document.body.appendChild(link);
					link.click();
					window.URL.revokeObjectURL(link.href);
				}
			});
		}).catch((err) => console.log(err));
	});
}

function formData(method, baseURL, url, params, response) {
	console.log(`formData【${baseURL}${url}】`);
	// if(hasSign){
	//   let enParams = params ? params : {}
	//   const encryptParam = encrypt(JSON.stringify(enParams))
	//   enParams.sign = encryptParam
	//   params = enParams
	// };
	const currentTime = new Date().getTime();
	return new Promise((resolve) => {
		Req({
			method,
			url,
			data: method === "POST" || method === "PUT" ? params : null,
			params: method === "GET" || method === "DELETE" ? params : null,
			baseURL,
			headers: {
				"Content-Type": "multipart/form-data;charset=UTF-8",
				Authorization: url === "/login" || url === "/textin/get" ? "" : `Bearer ${UserSession.getToken()}`,
				lid: currentTime,
				sign: encrypt(JSON.stringify(currentTime)),
			},
		}).then(function(res) {
			// eslint-disable-next-line eqeqeq
			if (res.data.code === 0) {
				if (res.data.data && typeof res.data.data === "object") {
					if (url === "/dialog/importCorpus" || url === "/doc/uploadAttach" || url === "/file/upload" || url === '/knowledgeCollect/doc/upload') {
						resolve(res.data);
					} else {
						resolve(res.data.data);
					}
				} else {
					resolve({
						code: 0,
						status: true,
						msg: res.data.msg ? res.data.msg : "操作成功",
						data: res.data.data,
					});
				}
			} else if (url === "/qa/import" || url === '/user/import') {
				checkStatus(res.data.code, res.data.message);
				resolve(res.data);
			} else {
				checkStatus(res.data.code, res.data.message);
			}
		}).catch((err) => {
			console.log(err.response.status);
			notification.open({
				key,
				message: "处理超时",
				icon: <Icon type='close-circle' style={{ color: "red" }} />,
			});
			resolve({ code: -1 });
			// checkStatus(err.response.status);
		});
	});
}

function downloadForPostWithCallBack(method, baseURL, url, params, response) {
	// if(hasSign){
	//   let enParams = params ? params : {}
	//   const encryptParam = encrypt(JSON.stringify(enParams))
	//   enParams.sign = encryptParam
	//   params = enParams
	// };
	const currentTime = new Date().getTime();
	console.log(`download【${baseURL}${url}】`);
	return new Promise((resolve) => {
		const headData = {
			"Content-Type": "application/json;charset=UTF-8",
			Authorization: url === "/login" ? "" : `Bearer ${UserSession.getToken()}`,
			lid: currentTime,
			sign: encrypt(JSON.stringify(currentTime)),
		};
		axios.post(baseURL + url, params, { headers: headData, responseType: "blob" }).then((res) => {
			const blob = new Blob([res.data]);
			const fileName = decodeURIComponent(
				res.headers["content-disposition"].split("=")[1]
			);
			resolve({
				status: true,
				msg: "操作成功",
				data: { blob, fileName, },
			});
		});
	});
}

function encrypt(encryptString) {
	const PUBLIC_KEY = "biaopin123456789";
	const key = CryptoJS.enc.Utf8.parse(PUBLIC_KEY);
	const srcs = CryptoJS.enc.Utf8.parse(encryptString);
	const encrypted = CryptoJS.AES.encrypt(srcs, key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7,
	});
	return encrypted.toString();
}

const http = {
	post(url, params, response) {
		return apiRobot("POST", baseSuffix, url, params, response);
	},
	get(url, params, response) {
		return apiRobot("GET", baseSuffix, url, params, response);
	},
	downloadFile(url, params, response) {
		return download("GET", baseSuffix, url, params, response);
	},
	uploadFile(url, params, response) {
		return formData("POST", baseSuffix, url, params, response);
	},
	getFormData(url, params, response) {
		return apiRobotFormData("GET", baseSuffix, url, params, response);
	},
	postFormData(url, params, response) {
		return apiRobotFormData("POST", baseSuffix, url, params, response);
	},
	downloadFileForPost(url, params, response) {
		return downloadForPost("POST", baseSuffix, url, params, response);
	},
	// 下载文件(防止影响之前的下载所以新建一个函数)
	downloadFileForPostWithCallBack(url, params, response) {
		return downloadForPostWithCallBack(
			"POST",
			baseSuffix,
			url,
			params,
			response
		);
	},
	// kefu接口
	postKf(url, params, response) {
		return apiRobot("POST", '/kefu-api', url, params, response);
	},
	getKf(url, params, response) {
		return apiRobot("GET", '/kefu-api', url, params, response);
	},
	postFormDataKf(url, params, response) {
		return apiRobotFormData("POST", '/kefu-api', url, params, response);
	},
};

export default http;
